package com.hhj.sharding.sphere.demo.controller;

import cn.hutool.core.util.RandomUtil;
import com.hhj.sharding.sphere.demo.base.PageVO;
import com.hhj.sharding.sphere.demo.base.Result;
import com.hhj.sharding.sphere.demo.model.ComplexParamVO;
import com.hhj.sharding.sphere.demo.model.entity.Complex;
import com.hhj.sharding.sphere.demo.service.IComplexService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Objects;

/**
 * 自定义策略接口
 *
 * @Description
 * @Author HHJ
 * @Date 2022-02-28 18:28
 */
@Slf4j
@RestController
@RequestMapping(value = "/v1/complex")
public class ComplexController {
    @Autowired
    private IComplexService complexService;

    /**
     * 测试分库分表-分页
     */
    @PostMapping("/findPage")
    public Result<PageVO> findPage(@RequestBody ComplexParamVO req) {
        log.info("自定义策略分库分表1-分页");
        return Result.success(complexService.findPage(req));
    }

    /**
     * 测试分库分表-新增
     */
    @PostMapping("/save")
    public Result<Boolean> save(@RequestBody ComplexParamVO req) {
        log.info("自定义策略分库分表1-新增");
        complexService.save(buildOrder(null, 1L + RandomUtil.randomLong(0, 10000000), 1L + RandomUtil.randomLong(0, 10000000), req.getCreateTime()));
        return Result.success(true);
    }

    /**
     * 测试分库分表 - 修改
     */
    @PostMapping("/updateById")
    public Result<Boolean> updateById(@RequestBody ComplexParamVO req) {
        log.info("自定义策略分库分表1- 修改");
        complexService.updateById(buildOrder(req.getId(), req.getUserId(), req.getOtherId(), req.getCreateTime()));
        return Result.success(true);
    }

    /**
     * 测试分库分表- 删除
     */
    @PostMapping("/deleteById")
    public Result<Boolean> deleteById(@RequestBody ComplexParamVO req) {
        log.info("自定义策略分库分表1- 删除");
        complexService.removeById(req.getId());
        return Result.success(true);
    }


    private Complex buildOrder(Long id, Long userId, Long otherId, Date date) {
        Complex order = new Complex();
        order.setId(id);
        order.setUserId(userId);
        order.setOtherId(otherId);
        if (Objects.nonNull(date)) {
            order.setCreateTime(date);
        } else {
            order.setCreateTime(new Date());
        }
        return order;
    }


}
